import router from '../router'
import store from '../store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, removeToken } from '@/utils/CookieUtils'
import getPageTitle from '@/utils/CliUtils'
import AjaxUtils from '@/utils/AjaxUtils'
import Layout from '@/layout'

const _import = require('../router/_import_' + process.env.NODE_ENV)

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/forget']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasUsername = store.getters.username
      if (hasUsername) {
        next()
      } else {
        await AjaxUtils.get('/user/getCurrentUser').then((response) => {
          store.dispatch('user/currentUserInfo', response.data)
          // 路由处理
          const menus = filterAsyncRouter(store.getters.menus)
          router.addRoutes(menus)
          global.antRouter = menus
        }).catch(() => {
          removeToken()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        })
        next({
          ...to,
          replace: true
        })
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

/**
 * 遍历后台传来的路由字符串，转换为组件对象
 * @param asyncRouterMap
 * @returns {*}
 */
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
